<script lang="ts" setup>
import { reactive, ref, watch, onMounted } from "vue"
import { getMerchantApplyDataApi, auditMerchantApplyApi } from "@/api/merchant-manage"
import { getCanteenListApi, getCanteenByIdApi } from "@/api/canteen"
import { type MerchantApplyData } from "@/api/merchant-manage/types/merchant-apply"
import { type FormInstance, ElMessage, ElMessageBox, TableInstance } from "element-plus"
import { Search, Refresh, Download, RefreshRight, Picture, Loading } from "@element-plus/icons-vue"
import { usePagination } from "@/hooks/usePagination"

defineOptions({
  // 命名当前组件
  name: "MerchantApply"
})

const loading = ref<boolean>(false)
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// 食堂信息映射
const canteenMap = ref<Record<number, { id: number, name: string }>>({});

// 获取所有食堂信息
const getCanteenList = () => {
  getCanteenListApi().then(({ data }) => {
    data.forEach((canteen: any) => {
      canteenMap.value[canteen.id] = canteen;
    });
  });
};

// 审核通过
const handleApprove = (row: MerchantApplyData) => {
  ElMessageBox.confirm(
    `<div style="line-height: 1.6;">
      <p><strong>请仔细核实以下信息后再确认审核通过：</strong></p>
      <p>• 商户名称：<span style="color: #409EFF; font-weight: bold;">${row.name}</span></p>
      <p>• <span style="color: #E6A23C; font-weight: bold;">子商户号：${row.subMchid}</span></p>
      <p>• 联系电话：${row.phone}</p>
      <br>
      <p style="color: #E6A23C; font-weight: bold;">⚠️ 特别提醒：</p>
      <p style="color: #E6A23C;">子商户号是微信支付的核心标识，一旦审核通过将无法修改。</p>
      <p style="color: #E6A23C;">错误的子商户号将导致支付功能完全失效！</p>
      <br>
      <p>确认子商户号 <strong>${row.subMchid}</strong> 准确无误后，点击确定继续。</p>
    </div>`,
    '审核确认 - 请重点核实子商户号',
    {
      confirmButtonText: '确认通过审核',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true,
      confirmButtonClass: 'el-button--warning',
      customClass: 'approve-confirm-dialog'
    }
  ).then(() => {
    auditMerchantApplyApi({ id: row.id, status: 1 }).then(() => {
      ElMessage.success("审核通过成功")
      getMerchantApplyData()
    })
  }).catch(() => {
    ElMessage.info('已取消审核')
  })
}

// 审核拒绝
const rejectFormRef = ref<FormInstance | null>(null)
const rejectDialogVisible = ref<boolean>(false)
const rejectForm = reactive({
  id: 0,
  rejectReason: ""
})

const handleReject = (row: MerchantApplyData) => {
  rejectDialogVisible.value = true
  rejectForm.id = row.id
  rejectForm.rejectReason = ""
}

const submitReject = () => {
  rejectFormRef.value?.validate((valid: boolean) => {
    if (!valid) return
    
    auditMerchantApplyApi({
      id: rejectForm.id,
      status: 2,
      rejectReason: rejectForm.rejectReason
    }).then(() => {
      ElMessage.success("审核拒绝成功")
      rejectDialogVisible.value = false
      getMerchantApplyData()
    })
  })
}

// 查询商户入驻申请数据
const merchantApplyData = ref<MerchantApplyData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive({
  name: "",
  phone: "",
  status: ""
})

const getMerchantApplyData = () => {
  loading.value = true
  getMerchantApplyDataApi({
    pageNo: paginationData.currentPage,
    pageSize: paginationData.pageSize,
    name: searchData.name || undefined,
    phone: searchData.phone || undefined,
    status: searchData.status ? Number(searchData.status) : undefined
  })
    .then(({ data }) => {
      paginationData.total = data.total
      merchantApplyData.value = data.list
    })
    .catch(() => {
      merchantApplyData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

const handleSearch = () => {
  paginationData.currentPage === 1 ? getMerchantApplyData() : (paginationData.currentPage = 1)
}

const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getMerchantApplyData, { immediate: true })

// 组件挂载时获取食堂列表
onMounted(() => {
  getCanteenList();
})
</script>

<template>
  <div class="app-container">
    <!-- 警告横幅 -->
    <el-alert
      title="重要提醒：审核商户申请时，请务必仔细核实子商户号的准确性！"
      description="子商户号是微信支付的关键标识，错误的子商户号将导致支付失败，影响商户正常营业。请在审核通过前再次确认子商户号与商户信息的匹配性。"
      type="warning"
      :closable="false"
      show-icon
      class="warning-banner"
    />
    
    <el-card v-loading="loading" shadow="never" class="search-wrapper">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="name" label="商户名称">
          <el-input v-model="searchData.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="phone" label="联系电话">
          <el-input v-model="searchData.phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="status" label="审核状态">
          <el-select v-model="searchData.status" placeholder="请选择" clearable style="width: 100px;">
            <el-option label="待审核" value="0" />
            <el-option label="审核通过" value="1" />
            <el-option label="审核拒绝" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
          <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card v-loading="loading" shadow="never">
      <div class="toolbar-wrapper">
        <div>
          <!-- 不需要新增和修改按钮 -->
        </div>
        <div>
          <el-tooltip content="下载">
            <el-button type="primary" :icon="Download" circle />
          </el-tooltip>
          <el-tooltip content="刷新当前页">
            <el-button type="primary" :icon="RefreshRight" circle @click="getMerchantApplyData" />
          </el-tooltip>
        </div>
      </div>
      <div class="table-wrapper">
        <el-table :data="merchantApplyData">
          <el-table-column prop="name" label="商户名称" align="center" />
          <el-table-column prop="subMchid" label="子商户号" align="center" class-name="highlight-column">
            <template #default="scope">
              <el-tag type="warning" effect="light" size="small">
                {{ scope.row.subMchid }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="logo" label="Logo" align="center">
            <template #default="scope">
              <el-image :src="scope.row.logo" style="width: 50px; height: 50px" fit="cover">
                <template #placeholder>
                  <el-icon>
                    <Picture />
                  </el-icon>
                </template>
                <template #error>
                  <el-icon>
                    <Loading />
                  </el-icon>
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="canteenId" label="所属食堂" align="center">
            <template #default="scope">
              <span>{{ canteenMap[scope.row.canteenId]?.name || '未知食堂' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="联系电话" align="center" />
          <el-table-column prop="address" label="商户地址" align="center" />
          <el-table-column prop="description" label="商户描述" align="center" show-overflow-tooltip />
          <el-table-column label="营业执照" align="center">
            <template #default="scope">
              <el-image 
                v-if="scope.row.licenseImage" 
                :src="scope.row.licenseImage" 
                style="width: 50px; height: 50px" 
                fit="cover"
                :preview-src-list="[scope.row.licenseImage]"
                :preview-teleported="true"
              >
                <template #placeholder>
                  <el-icon><Picture /></el-icon>
                </template>
                <template #error>
                  <el-icon><Loading /></el-icon>
                </template>
              </el-image>
              <span v-else>无图片</span>
            </template>
          </el-table-column>
          <el-table-column label="店内照片" align="center">
            <template #default="scope">
              <el-image 
                v-if="scope.row.shopImage" 
                :src="scope.row.shopImage" 
                style="width: 50px; height: 50px" 
                fit="cover"
                :preview-src-list="[scope.row.shopImage]"
                :preview-teleported="true"
              >
                <template #placeholder>
                  <el-icon><Picture /></el-icon>
                </template>
                <template #error>
                  <el-icon><Loading /></el-icon>
                </template>
              </el-image>
              <span v-else>无图片</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="审核状态" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.status === 0" type="info" effect="plain" disable-transitions>待审核</el-tag>
              <el-tag v-else-if="scope.row.status === 1" type="success" effect="plain" disable-transitions>审核通过</el-tag>
              <el-tag v-else type="danger" effect="plain" disable-transitions>审核拒绝</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="申请时间" align="center" />
          <el-table-column fixed="right" label="操作" width="180" align="center">
            <template #default="scope">
              <el-button v-if="scope.row.status === 0" type="success" text bg size="small" @click="handleApprove(scope.row)">通过</el-button>
              <el-button v-if="scope.row.status === 0" type="danger" text bg size="small" @click="handleReject(scope.row)">拒绝</el-button>
              <el-button v-if="scope.row.status === 2" type="primary" text bg size="small" @click="$event => {
                ElMessageBox.alert(scope.row.rejectReason, '拒绝原因', {
                  confirmButtonText: '确定'
                })
              }">查看原因</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 拒绝原因弹窗 -->
    <el-dialog v-model="rejectDialogVisible" title="拒绝原因" width="30%">
      <el-form ref="rejectFormRef" :model="rejectForm" :rules="{
        rejectReason: [{ required: true, message: '请输入拒绝原因', trigger: 'blur' }]
      }" label-width="100px">
        <el-form-item label="拒绝原因" prop="rejectReason">
          <el-input v-model="rejectForm.rejectReason" type="textarea" :rows="4" placeholder="请输入拒绝原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReject">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.warning-banner {
  margin-bottom: 20px;
  
  :deep(.el-alert__title) {
    font-size: 16px;
    font-weight: bold;
  }
  
  :deep(.el-alert__description) {
    font-size: 14px;
    line-height: 1.5;
    margin-top: 8px;
  }
}

.search-wrapper {
  margin-bottom: 20px;
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: center;
}

:deep(.highlight-column) {
  background-color: #fdf6ec !important;
}

:deep(.approve-confirm-dialog) {
  .el-message-box__message {
    text-align: left;
  }
}
</style>